﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QString userLand=Location::document + APP_ROOT;
    configFile=userLand + QString("/") + SP_CFG;

    view=new QWebEngineView(this);
    connect(view,&QWebEngineView::loadStarted,this,&MainWindow::onLoadStart);
    connect(view,&QWebEngineView::loadFinished,this,&MainWindow::onLoadFinished);
    connect(view,&QWebEngineView::titleChanged,this,&MainWindow::onTitleChanged);
    connect(view->page(),&QWebEnginePage::linkHovered,
            this,&MainWindow::onPageLinkHovered);

    //   connect(view,&QWebEngineView::urlChanged,this,&MainWindow::onUrlChanged);
    setCentralWidget(view);

    createNavbar();
    loadHomePage();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::loadHomePage()
{
    QSettings cfg(configFile,QSettings::IniFormat);
    cfg.setIniCodec("UTF-8");
    QString home=cfg.value("Main/home").toString();
    if(!home.isEmpty())
        loadUrl(home);
}

void MainWindow::createNavbar()
{
    createAppBar();
    updateFavoriteBar();
    updateMainBar();
}

void MainWindow::createAppBar()
{
    QMenu *menu=menuBar()->addMenu(QStringLiteral("文件(&F)"));
    menu->addAction(QStringLiteral("打开网址(&W)"),this,&MainWindow::do_openUrl,QKeySequence("Ctrl+W"));
    menu->addAction(QStringLiteral("打开文件(&O)"),this,&MainWindow::do_openFile,QKeySequence("Ctrl+O"));
    menu->addSeparator();
    menu->addAction(QStringLiteral("设为首页"),this,&MainWindow::do_setHomePage);
    menu->addAction(QStringLiteral("更新菜单栏"),this,&MainWindow::do_updateNavbar);
    menu->addSeparator();
    menu->addAction(QStringLiteral("退出(&W)"),this,&MainWindow::close,QKeySequence("Ctrl+Q"));
}

void MainWindow::updateFavoriteBar()
{
    if(!favItems.isEmpty())
        favItems.clear();

    QSqlQuery query;
    query.exec(QString("SELECT COUNT(time_) from %1")
                   .arg(P_TRACE));
    if(query.next())
    {
        int count=query.value(0).toInt();
        if(count < 2)
            return;

        QMenu *menu=menuBar()->addMenu(QStringLiteral("收藏夹(&B)"));
        query.exec(QString("SELECT label,COUNT(label) as tick from %1 GROUP BY label ORDER BY tick DESC LIMIT 20")
                       .arg(P_TRACE));
        while (query.next()) {
            QString label=query.value(0).toString();
            if(label.isEmpty())
                continue;
            QString detail=query.value(1).toString();
            menu->addAction(label);
            favItems.insert(label,detail);
        }

        if(!favItems.isEmpty())
            connect(menu,&QMenu::triggered,this,&MainWindow::processFavoriteAction);
    }
}

void MainWindow::updateMainBar()
{
    if(!items.isEmpty())
        items.clear();

    QSqlQuery query;
    query.exec(QString("select label from %1 where category='root'")
                   .arg(P_NAVBAR));
    while (query.next()) {
        QString category=query.value(0).toString();
        QMenu *menu=menuBar()->addMenu(category);

        QSqlQuery query;
        query.exec(QString("select label,detail from %1 where topic='%2'")
                       .arg(P_SITE)
                       .arg(category));
        while(query.next())
        {
            QString label=query.value(0).toString();
            if(label.isEmpty())
                continue;

            QString detail=query.value(1).toString();
            menu->addAction(label);
            items.insert(label,detail);
        }
        connect(menu,&QMenu::triggered,this,&MainWindow::processMainAction);
    }
}

void MainWindow::processFavoriteAction(QAction *action)
{
    QString label=action->text();
    QString detail=items.value(label);
    tickUp(label,detail);
    loadUrl(detail);
}

bool MainWindow::tickUp(const QString &label, const QString &detail)
{
    if(label.isEmpty())
        return false;

    QSqlQuery query;
    QString sql=QString("insert into %1 (time_,label,detail) values (?,?,?)").arg(P_TRACE);
    query.prepare(sql);
    query.addBindValue(CurrentDateTime);
    query.addBindValue(label);
    query.addBindValue(detail);
    if(!query.exec())
    {
        qDebug() << query.lastError().text();
        return false;
    }
    else
        return true;
}

void MainWindow::processMainAction(QAction *action)
{
    QString label=action->text();
    QString detail=items.value(label);
    tickUp(label,detail);
    loadUrl(detail);
}

void MainWindow::load(const QString &url)
{
    view->load(QUrl::fromUserInput(url));
}

void MainWindow::loadUrl(const QString &url)
{
    view->load(QUrl(url));
}

void MainWindow::onTitleChanged(const QString &title)
{
    setWindowTitle(title);
}

void MainWindow::onLoadStart()
{
    ui->statusbar->showMessage(QStringLiteral("页面加载中……"));
}

void MainWindow::onLoadFinished(bool flag)
{
    if(flag)
    {
        ui->statusbar->showMessage(view->url().toString());
    }
}

void MainWindow::onPageLinkHovered(const QString &url)
{
    targetUrl=url;
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton &&
        !targetUrl.isEmpty())
    {

    }
}

void MainWindow::do_setHomePage()
{
    QString home=view->url().toString();
    if(home.isEmpty())
        return;

    QSettings cfg(configFile,QSettings::IniFormat);
    cfg.setIniCodec("UTF-8");
    cfg.setValue("Main/home",home);
}

void MainWindow::do_openUrl()
{
    QString input=QInputDialog::getText(this,QStringLiteral("输入网址"),QStringLiteral("网址："));
    if(input.isEmpty())
        return;

    load(input);
}

void MainWindow::do_openFile()
{
    QUrl url=QFileDialog::getOpenFileUrl(this);
    if(url.isEmpty())
        return;

    view->load(url);
}

void MainWindow::do_updateNavbar()
{
    menuBar()->clear();
    createNavbar();
}
